//
//  HXCompanyInformTableViewController.m
//  KD
//
//  Created by 梅洋 on 16/8/5.
//  Copyright © 2016年 Whx. All rights reserved.
//

#import "HXCompanyInformTableViewController.h"

#import "HXAddMettingNotifyViewController.h"
#import "HXCompanyNotifyTableViewCell.h"
#import "HXCompanyNotifyDetailViewController.h"

#import "HXGetCompanyPersonalNotifyListModel.h"
#import "NSString+Frame.h"


@interface HXCompanyInformTableViewController ()

/**
 数据源
 */
@property (nonatomic,strong) NSMutableArray <HXGetCompanyPersonalNotifyListDetailModel *> * dataArray;

@property (nonatomic,assign) NSInteger pageNum;


@property (nonatomic, strong) NSTimer *timer;//极光登录注册定时器


@end

@implementation HXCompanyInformTableViewController

/**
 懒加载
 */
-(NSMutableArray<HXGetCompanyPersonalNotifyListDetailModel *> *)dataArray{
    
    if (_dataArray == nil) {
        
        _dataArray = [[NSMutableArray alloc] init];
    }
    
    return _dataArray;
}


-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    //    //加载数据
    //    [self loadCreateData];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"NOTIFICATION_HaveComeInIflyNotify" object:nil userInfo:nil];
}
-(void)viewDidDisappear:(BOOL)animated{
    
    [super viewDidDisappear:animated];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"NOTIFICATION_HaveComeOutIflyNotify" object:nil userInfo:nil];
    
}

#pragma mark ---------- 极光登陆 ---------------


// 设置别名
-(void)loginJPushUser:(NSString *)userName pwd:(NSString *)pwd{
    
    [JPUSHService setTags:[[NSSet alloc] init] alias:userName fetchCompletionHandle:^(int iResCode, NSSet *iTags, NSString *iAlias) {
        NSLog(@"********************* \n\nrescode: %d, \ntags: %@, \nalias: %@\n***********************\n", iResCode, iTags , iAlias);
        if (iResCode == 0) {
            [UserDefaultHandler saveUserDetault:@"yes" key:kIResCodeIs0Jpush];
//            [self.timer invalidate];
//            self.timer = nil;
        }else{
            if (![[UserDefaultHandler getUserDetault:kIResCodeIs0Jpush] isEqualToString:@"yes"]) {
                [self loginJPushUser:userName pwd:pwd];
            }
        }
    }];
}


#pragma mark ---------- 极光登陆 ---------------



- (void)viewDidLoad {
    [super viewDidLoad];
    
//    if (![[UserDefaultHandler getUserDetault:kIResCodeIs0Jpush] isEqualToString:@"yes"]) {
//        [self loginJPushUser:[UserDefaultHandler getUserDetault:kUsers_Alias] pwd:[UserDefaultHandler getUserDetault:kUsers_PassWord]];
//    }

    
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.navigationItem.title = @"通知";
    UIBarButtonItem * rightBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(rightBtnClick)];
    
    self.navigationItem.rightBarButtonItem = rightBtn;
    
    [self loadCreateNotification];
    
    //加载数据源
    [self loadCreateDataMethod];
    
}

/**
 注册通知 添加监听者
 */
-(void) loadCreateNotification{
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dealWithJPUSH:) name:@"NOTIFICATION_DealWithJPUSH_IflyNotify" object:nil];
}

/**
 通知的处理事件
 */
-(void)dealWithJPUSH:(NSNotification *)notification{
    
    NSLog(@"---------notification is %@",notification);
    
    [self loadCreateDataMethod];
}

/**
 销毁通知
 */
-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

/**
 加载加载的方法
 */
-(void)loadCreateDataMethod{
    
    self.tableView.mj_header=[AWRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(laodCreateData)];
    self.tableView.mj_footer=[AWRefreshFooder footerWithRefreshingTarget:self refreshingAction:@selector(getMoreTableViewData)];
    self.tableView.mj_footer.automaticallyChangeAlpha = YES;
    self.tableView.mj_footer.automaticallyHidden = NO;
    [self.tableView.mj_header beginRefreshing];
}


/**
 获取数据源
 */
-(void)laodCreateData{
    
    self.pageNum = 0;
    
    [SVProgressHUD showWithStatus:@"正在加载..."];
    [NetworkAPI getCompanyPersonalNotifyListWithOrgCode:[UserDefaultHandler getUserDetault:kUsers_Organization]
                                               PageSize:@"10"
                                                PageNum:[NSString stringWithFormat:@"%ld",(long)self.pageNum]
                                                Success:^(HXGetCompanyPersonalNotifyListModel *result) {
                                                    
                                                    if ([result.code isEqualToString:@"200"]) {
                                                        
                                                        [self.tableView.mj_footer resetNoMoreData];
                                                        [SVProgressHUD showSuccessWithStatus:@"刷新成功"];
                                                        [self.tableView.mj_header endRefreshing];
                                                        
                                                        self.pageNum ++;
                                                        [self.dataArray removeAllObjects];
                                                        self.dataArray = [result.result mutableCopy];
                                                        [self.tableView reloadData];
                                                        
                                                        if ([result.result count] < 10) {
                                                            [self.tableView.mj_footer endRefreshingWithNoMoreData];
                                                            self.tableView.mj_footer.alpha = 1.0f;
                                                            return;
                                                        }
                                                        
                                                    }
                                                    else if([result.code isEqualToString:@"400"]){
                                                        [SVProgressHUD showErrorWithStatus:@"暂无数据"];
                                                        [self.tableView.mj_header endRefreshing];
                                                        [self.tableView.mj_footer endRefreshingWithNoMoreData];
                                                        self.tableView.mj_footer.alpha = 1.0f;
                                                    }else{
                                                        [SVProgressHUD showErrorWithStatus:@"暂无更多"];
                                                        [self.tableView.mj_header endRefreshing];
                                                    }
                                                    
                                                } failure:^(NSError *err) {
                                                    [SVProgressHUD showErrorWithStatus:@"网络错误!"];
                                                }];
}

/**
 加载更多数据
 */
-(void)getMoreTableViewData {
    
    [SVProgressHUD showWithStatus:@"正在加载..."];
    
    [NetworkAPI getCompanyPersonalNotifyListWithOrgCode:[UserDefaultHandler getUserDetault:kUsers_Organization]
                                               PageSize:@"10"
                                                PageNum:[NSString stringWithFormat:@"%ld",(long)self.pageNum]
                                                Success:^(HXGetCompanyPersonalNotifyListModel *result) {
                                                    
                                                    [SVProgressHUD dismiss];
                                                    if ([result.code isEqualToString:@"200"]) {
                                                        
                                                        if ([result.result count] == 0) {
                                                            [self.tableView.mj_footer endRefreshingWithNoMoreData];
                                                            self.tableView.mj_footer.alpha = 1.0f;
                                                            return;
                                                        }else if ([result.result count] < 10) {
                                                            [self.dataArray addObjectsFromArray:result.result];
                                                            [self.tableView reloadData];
                                                            [self.tableView.mj_footer endRefreshingWithNoMoreData];
                                                            self.tableView.mj_footer.alpha = 1.0f;
                                                        }else {
                                                            self.pageNum++;
                                                            [self.dataArray addObjectsFromArray:result.result];
                                                            [self.tableView reloadData];
                                                            [self.tableView.mj_footer endRefreshing];
                                                            self.tableView.mj_footer.alpha = 0;
                                                        }
                                                        
                                                    }
                                                    else if([result.code isEqualToString:@"400"]){
                                                        [SVProgressHUD showErrorWithStatus:@"暂无数据"];
                                                        [self.tableView.mj_header endRefreshing];
                                                        [self.tableView.mj_footer endRefreshingWithNoMoreData];
                                                        self.tableView.mj_footer.alpha = 1.0f;
                                                    }else{
                                                        [SVProgressHUD showErrorWithStatus:@"暂无更多"];
                                                        [self.tableView.mj_footer endRefreshing];
                                                        self.tableView.mj_footer.alpha = 0;
                                                    }
                                                    
                                                    
                                                } failure:^(NSError *err) {
                                                    
                                                    [SVProgressHUD showErrorWithStatus:@"网络错误!"];
                                                    
                                                }];
    
}


/**
 点击事件
 */
-(void)rightBtnClick {
    
    HXAddMettingNotifyViewController * addVC = [[HXAddMettingNotifyViewController alloc] init];
    [self.navigationController pushViewController:addVC animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    //#warning Incomplete implementation, return the number of sections
    
    return self.dataArray.count;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    //#warning Incomplete implementation, return the number of rows
    return 1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HXCompanyNotifyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HXCompanyNotifyTableViewCell" ];
    
    
    if (cell == nil) {
        
        cell = [[[NSBundle mainBundle] loadNibNamed:@"HXCompanyNotifyTableViewCell" owner:nil options:nil] objectAtIndex:0];
    }
    
    HXGetCompanyPersonalNotifyListDetailModel * model = self.dataArray[indexPath.section];
    
    cell.detailModel = model;
    
    return cell;
}

/**
 使用组头视图 当做分界线  假象
 */
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 2.f;
}

/**
 返回单元格的高度
 */
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    HXGetCompanyPersonalNotifyListDetailModel * model = self.dataArray[indexPath.section];
    
    CGFloat height = 62.f - 22.f;
    
    if (model.Title.length > 0) {
        
        height = height + [model.Title heightWithFont:[UIFont systemFontOfSize:18] withinWidth:HXSCREEN_WIDTH-44-8];
    }else{
        
        height = 62.f;
    }
    
    return height;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    HXGetCompanyPersonalNotifyListDetailModel * model = self.dataArray[indexPath.section];
    
    HXCompanyNotifyDetailViewController * detailVc = [[HXCompanyNotifyDetailViewController alloc] init];
    
    detailVc.messageId = model.MessageID;
    
    [self.navigationController pushViewController:detailVc animated:YES];
}



@end
